package cn.swing.ushare.user.webapi.service;


import cn.swing.ushare.common.ex.ServiceException;
import cn.swing.ushare.common.web.State;
import cn.swing.ushare.pojo.dto.*;
import cn.swing.ushare.pojo.entity.User;
import cn.swing.ushare.pojo.vo.*;
import cn.swing.ushare.user.service.IUserService;
import cn.swing.ushare.user.webapi.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {


    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetailsVO getUserDetailsById(Integer id) {
        return userMapper.getUserDetailsById(id);
    }

    @Override
    public int updateEnabledById(Integer id) {
        UserDetailsVO userDetails = userMapper.getUserDetailsById(id);
        int change = 0;
        if (userDetails.getIsEnable() == 1) {
            change = userMapper.updateUserEnableById(id, 0);
            userMapper.insertOperationLog("用户管理", "更新", logOperation(), "禁用用户:'" + userDetails.getNickname() + "'登录");
        } else {
            change = userMapper.updateUserEnableById(id, 1);
            userMapper.insertOperationLog("用户管理", "更新", logOperation(), "启动用户:'" + userDetails.getNickname() + "'登录");
        }
        return change;

    }


    @Override
    public Integer countUser(String nickname) {
        return userMapper.userCount(nickname);
    }

    /****************************************ljk改**********************************/

    @Override
    public List<UserListVO> userList(UserLimitSimpleDTO userLimitSimpleDTO) {
        List<UserListVO> userListVOS = userMapper.userList(userLimitSimpleDTO.getNickname(), userLimitSimpleDTO.getPage());
        System.out.println(userListVOS);
        for (UserListVO userListVO : userListVOS) {
            if (userListVO.getIsEnable().equals("1")) {
                userListVO.setIsEnable("true");
            } else {
                userListVO.setIsEnable("false");
            }
        }
        return userListVOS;
    }

    @Override
    public PersonalSimpleVO getPersonalSimple() {
        return userMapper.getPersonalSimple(logOperation());
    }

    @Override
    public Integer updatePassByUsername(UserChangePasswordDTO userChangePasswordDTO) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        userChangePasswordDTO.setUsername((String) principal);

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String oldPassword = userChangePasswordDTO.getOldPass();

        System.out.println("userChangePasswordDTO = " + userChangePasswordDTO);

        PersonalSimpleVO simpleVO = userMapper.getPersonalSimple(userChangePasswordDTO.getUsername());
        if (!passwordEncoder.matches(oldPassword, simpleVO.getPassword())) {
            throw new ServiceException(State.ERR_PASSWORD_OR_USERNAME, "原密码错误");
        }
        userChangePasswordDTO.setNewPass(passwordEncoder.encode(userChangePasswordDTO.getNewPass()));
        System.out.println("改密码之后");
        System.out.println("userChangePasswordDTO = " + userChangePasswordDTO);
        return userMapper.updatePassByUsername(userChangePasswordDTO);
    }

    /****************************************ljk改**********************************/
    @Override
    public int updateUserRole(UserUpdateRoleDTO userUpdateRoleDTO) {
        int change = 0;
        UserDetailsVO userDetails = userMapper.getUserDetailsById(userUpdateRoleDTO.getId());
        List<RoleListVO> roleList = userMapper.roleList();
        for (RoleListVO roleListVO : roleList) {
            if (userUpdateRoleDTO.getRoleName().equals(roleListVO.getRoleName())) {
                change = userMapper.updateUserRole(userUpdateRoleDTO.getId(), roleListVO.getId());
                userMapper.insertOperationLog("用户管理", "更新", logOperation(), "更新 " + userDetails.getNickname() + "角色身份");
            }
        }
        return change;
    }


    @Override
    public UserCenterDetailsVO getUserCenterDetailsById(Integer id) {

        return userMapper.getUserCenterDetails(id);
    }

    @Override
    public UserCenterHeaderVO getUserCenterHeaderById(Integer id) {
        return userMapper.getUserCenterHeaderById(id);
    }

    @Override
    public List<RoleListVO> roleList() {
        return userMapper.roleList();
    }

    @Override
    public List<CategorySimpleVO> getUserCenterCategory(Integer id) {
        return userMapper.getUserCenterCategory(id);
    }

    @Override
    public List<CategorySimpleVO> getAllCategory(Integer id) {
        return userMapper.getAllCategory(id);
    }

    @Override
    public String getCurrentAvatar(Integer id) {
        return userMapper.getCurrentAvatar(id);
    }

    @Override
    public UserCenterHeaderVO getArticleDetailsUserInfoById(Integer id) {
        return userMapper.getArticleDetailsUserInfoById(id);
    }

    @Override
    public List<UserSimpleVO> getAllFollows(Integer id) {
        return userMapper.getAllFollows(id);
    }


    @Override
    public List<UserSimpleVO> getAllFans(Integer id) {
        return userMapper.getAllFans(id);
    }

    @Override
    public boolean isFollow(Integer id, Integer userId) {
        List<Integer> list = userMapper.isFollow(id);
        if (list.size() == 0)
            return false;
        if (list.contains(userId))
            return true;
        else
            return false;
    }

    @Override
    public void insertRole(String roleName) {
        userMapper.insertOperationLog("用户管理", "插入", logOperation(), "插入[" + roleName + "]角色身份");
        userMapper.insertRole(roleName);
    }

    @Override
    public void deleteRoleById(Integer id) {
        userMapper.deleteRoleById(id);
        userMapper.insertOperationLog("用户管理", "删除", logOperation(), "删除角色");

    }

    @Override
    public boolean login(UserLoginDTO userLoginDTO) {
        userMapper.updateLastLoginTime(userLoginDTO.getUsername());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userLoginDTO.getUsername());
        queryWrapper.eq("password", userLoginDTO.getPassword());
        return true;
    }

    @Override
    public int updateUserCenterDetails(UserCenterDetailsDTO userCenterDetails) {
        userMapper.insertOperationLog("用户管理", "更新", logOperation(), "用户中心更新用户详细信息");
        return userMapper.updateUserCenterDetails(userCenterDetails);
    }


    @Override
    public int deleteUserCenterCategoryById(Integer userId) {
        userMapper.insertOperationLog("类别管理", "删除", logOperation(), "根据id删除用户中心类别信息");
        return userMapper.deleteUserCenterCategoryById(userId);
    }

    @Override
    public int insertUserCenterCategories(List<UserCenterCategoryDTO> userCenterCategories) {
        userMapper.insertOperationLog("类别管理", "插入", logOperation(), "用户中心添加用户类别信息");
        return userMapper.insertUserCenterCategories(userCenterCategories);
    }


    @Override
    public List<PermissionListVO> getPermissions() {
        return userMapper.getPermissions();
    }


    @Override
    public List<SelectPermissionVO> getPermissionById(Integer roleId) {
        return userMapper.getPermissionById(roleId);
    }

    @Override
    public int changeRoleOperation(List<ChangeRoleOperationDTO> changeRoleOperations) {
        if (changeRoleOperations.size() == 1) {
            userMapper.deleteNull();
            int change = userMapper.deleteRoleOperationById(changeRoleOperations.get(1).getRoleId());
            userMapper.deleteNull();
            return 0;
        }
        int change = userMapper.deleteRoleOperationById(changeRoleOperations.get(1).getRoleId());
        userMapper.deleteNull();
        userMapper.insertOperationLog("角色管理", "更新", logOperation(), "更改操作权限分配");
        return userMapper.changeRoleOperation(changeRoleOperations);
    }

    @Override
    public String insertRegister(UserRegisterSimpleDTO userRegisterSimpleDTO) {
        if (userMapper.selectNickname(userRegisterSimpleDTO.getNickname()) == 0) {
            UserRegisterDTO user = new UserRegisterDTO();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            Integer id = userMapper.selectMaxId();
            user.setUsername("UU" + (id + 1));
            user.setNickname(userRegisterSimpleDTO.getNickname());
            user.setPassword(passwordEncoder.encode(userRegisterSimpleDTO.getPassword()));
            user.setDescription("此人很懒没有简介");
            user.setAvatar("https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png");
            user.setGender('M');
            user.setLoveCount(0);
            user.setFollowCount(0);
            user.setFanCount(0);
            userMapper.insertUserRole((id + 1), 1);
            userMapper.insertRegister(user);
            return "用户注册成功";
        } else {
            return "用户注册失败";
        }
    }

    @Override
    public int insertFollow(Integer id, Integer userId) {
        return userMapper.insertFollow(id, userId);
    }

    @Override
    public int deleteFollow(Integer id, Integer userId) {
        return userMapper.deleteFollow(id, userId);
    }

    //修改用户头像
    @Override
    public int updateUserAvatar(Integer userId, String imgUrl) {
        imgUrl = "http://localhost:9092/articlePictures/" + imgUrl;
        System.out.println("imgUrl = " + imgUrl);
        return userMapper.updateUserAvatar(userId, imgUrl);
    }

    @Override
    public String selectUsernameByNickname(String nickname) {
        System.out.println("UserServiceImpl.selectUsernameByNickname");
        System.out.println("nickname = " + nickname);

        return userMapper.selectUsernameByNickname(nickname);
    }

    // 日志操作
    private String logOperation() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = (String) principal;
        return username;
    }

    public Integer getLoginUserId() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = (String) principal;
        if (!username.equals("anonymousUser")) {
            System.out.println(username);
            System.out.println(username.substring(2));
            Integer userId = Integer.valueOf(username.substring(2));
            return userId;
        }
        return null;
    }


    @Override
    public String PerfectInformation(Integer id) {
        UserDetailsVO userDetailsVO = userMapper.getUserDetailsById(id);
        if (userDetailsVO.getPhoneNumber() == null || userDetailsVO.getEmail() == null || userDetailsVO.getBirthday() == null) {
            return "用户信息未完善";
        } else {
            return "用户信息已完善";
        }
    }

    @Override
    public Integer addUserFollowers(Integer userId) {
        return userMapper.addUserFollowers(userId);
    }

    @Override
    public Integer subUserFollowers(Integer userId) {
        return userMapper.subUserFollowers(userId);
    }

    @Override
    public Integer addUserFans(Integer userId) {
        return userMapper.addUserFans(userId);
    }

    @Override
    public Integer subUserFans(Integer userId) {
        return userMapper.subUserFans(userId);
    }
}
